package com.sxpro;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

class StringExtractor {

    // 定义状态机的状态
    enum State {
        START,          // 初始状态
        IN_STRING,      // 读取字符串
        ESCAPE          // 处理转义字符
    }

    // 提取文件中的所有字符串
    public List<String> extractStrings(String filePath) throws IOException {
        List<String> strings = new ArrayList<>();
        State currentState = State.START;
        StringBuilder currentString = new StringBuilder();

        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            int character;
            while ((character = reader.read()) != -1) {
                char ch = (char) character;

                switch (currentState) {
                    case START:
                        // 如果遇到双引号，进入字符串读取状态
                        if (ch == '"') {
                            currentState = State.IN_STRING;
                        }
                        break;

                    case IN_STRING:
                        // 如果遇到转义符号，进入处理转义字符状态
                        if (ch == '\\') {
                            currentState = State.ESCAPE;
                        } else if (ch == '"') {
                            // 如果遇到双引号，表示字符串结束
                            strings.add(currentString.toString());
                            currentString.setLength(0);  // 清空当前字符串
                            currentState = State.START;
                        } else {
                            // 正常字符，添加到当前字符串
                            currentString.append(ch);
                        }
                        break;

                    case ESCAPE:
                        // 如果是转义字符，直接将下一个字符添加到字符串中
                        currentString.append(ch);
                        currentState = State.IN_STRING;  // 返回到字符串读取状态
                        break;
                }
            }
        }
        return strings;
    }

    // 测试方法
    public static void main(String[] args) {
        StringExtractor extractor = new StringExtractor();
        try {
            List<String> strings = extractor.extractStrings("example.java");
            for (String str : strings) {
                System.out.println(str);  // 打印提取的每一个字符串
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
